package com.pearlsoft.webapp.core.dataset;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.pearlsoft.commons.utils.TypesUtil;

/**
 * 
 * Query
 * 
 * @Creator haitingr
 * @Create-DateTime 2011-10-25
 */
public class Query {

	public static final int DEFAULT_PAGE_SIZE = 10;

	private int pageSize = DEFAULT_PAGE_SIZE;

	private int start = 0;

	protected List<Condition> conditions = new ArrayList<Condition>();

	protected String datasetName;

	protected String handler;

	protected String handlerMethod = "handler";

	protected Map<String, Object> map = new HashMap<String, Object>();

	public Query() {
		super();
	}

	public Query(String datasetName) {
		this.datasetName = datasetName;
	}

	public Query(String datasetName, List<Condition> conditions) {
		this(datasetName);
		this.conditions.addAll(conditions);
		map = this.toMap();
	}

	public String getHandlerMethod() {
		return handlerMethod;
	}

	public void setHandlerMethod(String handlerMethod) {
		this.handlerMethod = handlerMethod;
	}

	public Iterator<Condition> iterator() {
		return conditions.iterator();
	}

	public Map<String, Object> toMap() {
		Map<String, Object> map = new HashMap<String, Object>();
		for (Condition condition : this.conditions) {
			map.put(condition.getFieldName(), TypesUtil.toString(condition.getValue()));
		}
		return map;
	}

	public void fromMap(Map<String, Object> map) {
		for (String key : map.keySet()) {
			Condition condition = new Condition(key, map.get(key));
			this.conditions.add(condition);
		}
	}

	public void add(String key, Object value) {
		Condition condition = new Condition(key, value);
		this.map.put(key, value);
		this.conditions.add(condition);
	}
	
	public Object get(String key){
		return this.map.get(key);
	}

	public void remove(String key) {
		this.conditions.remove(new Condition(key, null));
		this.map.remove(key);
	}

	public String getDatasetName() {
		return datasetName;
	}

	public void setDatasetName(String datasetName) {
		this.datasetName = datasetName;
	}

	public String getHandler() {
		return handler;
	}

	public void setHandler(String handler) {
		this.handler = handler;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public int getStart() {
		return start;
	}

	public void setStart(int start) {
		this.start = start;
	}

	public List<Condition> getConditions() {
		return conditions;
	}

	public void setConditions(List<Condition> conditions) {
		this.conditions = conditions;
		this.map = toMap();
	}

	/**
	 * @return the map
	 */
	public Map<String, Object> getMap() {
		return map;
	}


}
